<?php

require_once (fvSite::$fvConfig->get("path.entity") . 'sections.class.php') ;

class SectionsManager extends fvRootManager {

	protected function __construct () {
		$objectClassName = substr(__CLASS__, 0, -7);
		 
		$this->rootObj = new $objectClassName();
	}

	static function getInstance()
	{
		static $instance;
		if (!isset($instance)) {
			$instance = new self();
		}
		return $instance;
	}

	function htmlSelect ($field, $empty = "", $where = null, $order = null, $limit = null, $args = array()) {
		$result = array('0' => 'корневой пункт меню');

		if (!is_array($args)) $args = array(($args)?$args:'');

		$result = $result + parent::htmlSelect($field, $empty, $where, $order, $limit, $args);
		return $result;
	}

	function getSectionTree($where = null, $args = array()) {
		$query = "SELECT q.* FROM " . $this->rootObj->getTableName() . " q
left join " . $this->rootObj->getTableName() . " q_p on q_p.id = q.parent_id";
		if (!empty($where)) $query .= "\nWHERE (" . $where . ")";
		$query .= "\norder by q.menu_order, q.id, q.parent_id, IF (q.parent_id = 0, (q.menu_order + 1)*100000, (q_p.menu_order + 1)*100000 + (q.menu_order + 1)) ASC";
		$res = fvSite::$DB->query($query, $params);

		$result = array();

		if (!DB::isError($res)) {
			while ($row = $res->fetchRow()) {
				$o = clone $this->rootObj;
				$o->hydrate($row);
				$result[] = $o;
			}
		}

		return $result;
	}

	function getPath($id){
		do{
			$Section = SectionsManager::getInstance()->getByPk($id);
			if ($Section){
				$path[] = array ("id" => $Section->getPk(), "title" => $Section->title);
				$id = $Section->parent_id;
			}
			else{
				$path[] = array ("id" => 0, "title" => "Путь не найден");
				$id = 0;
			}
		} while ($id!=0);
		return array_reverse($path);
	}
	
	function getSectionIDs($id){
		$stop = 1;
     	$result = array() ;
     	$params_tmp = array($id);
		do{
			$Sections = SectionsManager::getInstance()->getAll("parent_id in (".implode(',', $params_tmp).")");
			$params_tmp = array ();
			if (count($Sections)){
				foreach ($Sections as $Section){
					$params_tmp[] = $Section->getPk();
					$result = array_unique(array_merge($params_tmp, $result));
				}
			}
			else{
				$stop = 0;
			}
		} while ($stop!=0);
		$result[] = $id;
		return $result;
	}
	
	function getSections($currentSection){
		$kishka = array();
		$fvTree = new fvTree($this->getSectionTree(), false);
		$kishka = $fvTree->get_leafs($this->getSectionTree(),$currentSection);
		return $kishka;
	}
}
